package <%=packageName%>.config;

import static springfox.documentation.schema.AlternateTypeRules.newRule;

import java.lang.reflect.Proxy;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;

import com.fasterxml.classmate.TypeResolver;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

<%if(dataRest) {%>
import org.springframework.context.annotation.Import;
import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration;
<%}%>

<%
var appName =pascalCase(name);
var docketName = camelCase(name)+"API";
%>


@Configuration
<%if(dataRest) {%>
@Import(SpringDataRestConfiguration.class)
<%}%>
public class <%=appName%>Config {

	
	@Bean("<%=docketName%>")
	@ConditionalOnProperty(prefix = "tank", name = "swagger-open", havingValue = "true")
	public Docket create<%=appName%>API(TypeResolver typeResolver) {
		//这里采用包扫描的方式来确定要显示的接口
		Predicate<RequestHandler> apiPredicate = RequestHandlerSelectors.basePackage("<%=packageName%>.controller");
		<%if(dataRest) {%>
		String repositoryRestPackage = "<%=packageName%>.dao";
		apiPredicate = apiPredicate.or(r->{ // spring data rest 
			HandlerMethod handlerMethod = r.getHandlerMethod();
			if(handlerMethod == null ||!(handlerMethod.getBean() instanceof Proxy))
				return false;
			return  Arrays.stream(handlerMethod.getBeanType().getInterfaces()).anyMatch(clz->clz.getPackage().getName().startsWith(repositoryRestPackage));
		});
		<%}%>
		List<AlternateTypeRule> datetimeTypeRules = new ArrayList<>();
		for(Class<?> datetimeClz:new Class[] {LocalDate.class, LocalDateTime.class, Instant.class, ZonedDateTime.class}) {
			datetimeTypeRules.add(newRule(datetimeClz,String.class));
			datetimeTypeRules.add(newRule(typeResolver.resolve(List.class, typeResolver.resolve(datetimeClz)),
					typeResolver.resolve(List.class, typeResolver.resolve(String.class))));
		}
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(new ApiInfoBuilder()
						.title("<%=appName%>服务接口")
						.version("<%=version%>")
						.build())
				.groupName("<%=appName%>")
				.select()
				.apis(apiPredicate )    
				.paths(PathSelectors.any())
				.build()
				.alternateTypeRules(datetimeTypeRules.toArray(new AlternateTypeRule[0]));
	}
	
}
